package com.hgsoft.pubsv.component.apifilter.filter;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.springframework.util.StreamUtils;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import lombok.extern.slf4j.Slf4j;
@Slf4j
public class EncryptionReqestWrapper extends HttpServletRequestWrapper  {
	
	private byte[] requestBody = new byte[0];

    private Map<String, Object> paramMap = new HashMap<>();

	public EncryptionReqestWrapper(HttpServletRequest request) {
		super(request);
		try {
			requestBody = StreamUtils.copyToByteArray(request.getInputStream());
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	
	@Override
	public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream bais = new ByteArrayInputStream(requestBody);
        return new ServletInputStream() {
            @Override
            public int read() throws IOException {
                return bais.read();
            }
 
            @Override
            public boolean isFinished() {
                return false;
            }
 
            @Override
            public boolean isReady() {
                return true;
            }
 
            @Override
            public void setReadListener(ReadListener listener) {
 
            }
        };
	}

	public String getRequestData() {
		return new String(requestBody);
	}
	
	public void setRequestData(String requestData) {
		this.requestBody = requestData.getBytes();
	}

    public void setParamMap(Map<String, Object> paramMap) {
        this.paramMap = paramMap;
    }
    
    /** 
     * 保存文件参数 
     * @param name 
     * @param value 
     */  
    public void setParameter(String name, CommonsMultipartFile value) {  
    	log.info("setParameter:"+name);
        this.paramMap.put(name, value);  
    } 

    @Override
    public String getParameter(String name) {
        return this.paramMap.get(name)==null?null:this.paramMap.get(name).toString();
    }

    @Override
    public String[] getParameterValues(String name) {
	    if (paramMap.containsKey(name)) {
            return new String[] { getParameter(name) };
        }
        return super.getParameterValues(name);
    }
}
